<template>
  <div class="page-wrap">
    <el-card shadow="never" class="mb-12">
      <div class="toolbar">
        <el-date-picker v-model="range" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        <el-button @click="refresh">刷新</el-button>
      </div>
      <el-table :data="rows" border stripe>
        <el-table-column prop="operator" label="员工" width="140" />
        <el-table-column prop="salesQty" label="销售单数" width="120" />
        <el-table-column prop="items" label="件数" width="120" />
        <el-table-column prop="amount" label="金额(估)" width="140" />
        <el-table-column prop="avgAmount" label="客单价(估)" width="140" />
      </el-table>
    </el-card>

    <!-- 数据透视表（拖拽字段面板） -->
    <el-card shadow="never">
      <div class="panel">
        <div class="pool">
          <div class="title">字段池</div>
          <div class="chips">
            <span
              v-for="d in dimensions"
              :key="'dim-'+d.value"
              class="chip dim"
              draggable="true"
              @dragstart="onPoolDragStart('dim', d.value)"
            >{{ d.label }}</span>
            <span
              v-for="m in metrics"
              :key="'met-'+m.value"
              class="chip met"
              draggable="true"
              @dragstart="onPoolDragStart('met', m.value)"
            >{{ m.label }}</span>
          </div>
        </div>
        <div class="zones">
          <div class="zone" @dragover.prevent @drop="onZoneDrop('rows')">
            <div class="zone-title">行维度</div>
            <div class="chips">
              <span
                v-for="(f,idx) in rowsSelected"
                :key="'rows-'+f"
                class="chip dim"
                draggable="true"
                @dragstart="onChipDragStart('rows', idx, f)"
                @dragover.prevent
                @drop="onChipDrop('rows', idx)"
              >{{ labelOf(f) }}<i class="rm" @click.stop="removeField('rows', f)">×</i></span>
            </div>
          </div>
          <div class="zone" @dragover.prevent @drop="onZoneDrop('cols')">
            <div class="zone-title">列维度</div>
            <div class="chips">
              <span
                v-for="(f,idx) in colsSelected"
                :key="'cols-'+f"
                class="chip dim"
                draggable="true"
                @dragstart="onChipDragStart('cols', idx, f)"
                @dragover.prevent
                @drop="onChipDrop('cols', idx)"
              >{{ labelOf(f) }}<i class="rm" @click.stop="removeField('cols', f)">×</i></span>
            </div>
          </div>
          <div class="zone" @dragover.prevent @drop="onZoneDrop('vals')">
            <div class="zone-title">指标</div>
            <div class="chips">
              <span
                v-for="(f,idx) in valsSelected"
                :key="'vals-'+f"
                class="chip met"
                draggable="true"
                @dragstart="onChipDragStart('vals', idx, f)"
                @dragover.prevent
                @drop="onChipDrop('vals', idx)"
              >{{ labelMetric(f) }}<i class="rm" @click.stop="removeField('vals', f)">×</i></span>
            </div>
          </div>
        </div>
      </div>

      <div class="toolbar mt-8">
        <el-button type="primary" @click="renderPivot">分析</el-button>
      </div>
      <div ref="s2Container" class="s2-container"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { useStockStore } from '@/stores/stock.js'
import { PivotSheet } from '@antv/s2'
import '@antv/s2/dist/style.min.css'

const stock = useStockStore()
const range = ref([])
const rows = ref([])

// 透视表配置
const dimensions = [
  { label: '日期', value: 'date' },
  { label: '门店/仓库', value: 'warehouse' },
  { label: '员工', value: 'operator' },
]
const metrics = [
  { label: '销售单数', value: 'records' },
  { label: '件数', value: 'items' },
  { label: '金额(估)', value: 'amount' },
]
const rowsSelected = ref(['operator'])
const colsSelected = ref(['date'])
const valsSelected = ref(['items', 'amount'])
const s2Container = ref(null)
let s2 = null

onMounted(()=>{ if(!stock.stockList.length) stock.initializeStock(); refresh() })

function inRange(dateIso){
  if (!range.value || range.value.length !== 2) return true
  const [start, end] = range.value
  const d = new Date(dateIso).toISOString().slice(0,10)
  return (!start || d >= start) && (!end || d <= end)
}

function refresh(){
  // 使用库存历史中 outbound 的 operator 做简化统计
  const outbound = stock.getStockHistory(null, 'outbound').filter(r => inRange(r.date))
  const map = {}
  outbound.forEach(r => {
    const key = r.operator || '—'
    if (!map[key]) map[key] = { operator: key, salesQty: 0, items: 0, amount: 0 }
    map[key].salesQty += 1
    map[key].items += Number(r.quantity || 0)
    // 简化：金额无法从历史取到售价，这里先按单价字段或0
    map[key].amount += Number(r.price || 0) * Number(r.quantity || 0)
  })
  rows.value = Object.values(map).map(x => ({ ...x, avgAmount: x.salesQty ? Number((x.amount / x.salesQty).toFixed(2)) : 0 }))

  // 同步刷新透视表
  renderPivot()
}

// 辅助：日期格式化到日
function formatDate(iso){
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return '—'
  const y = d.getFullYear()
  const m = String(d.getMonth()+1).padStart(2,'0')
  const day = String(d.getDate()).padStart(2,'0')
  return `${y}-${m}-${day}`
}

function buildRecords(){
  const outbound = stock.getStockHistory(null, 'outbound').filter(r => inRange(r.date))
  return outbound.map(r => ({
    date: formatDate(r.date),
    warehouse: r.warehouse || '—',
    operator: r.operator || '—',
    records: 1,
    items: Number(r.quantity || 0),
    amount: Number(r.price || 0) * Number(r.quantity || 0),
  }))
}

function renderPivot(){
  if (!s2Container.value) return
  const data = buildRecords().map(rec => {
    const row = { ...rec }
    rowsSelected.value.forEach(d => { row[d] = rec[d] || '—' })
    colsSelected.value.forEach(d => { row[d] = rec[d] || '—' })
    row.items = Number(row.items || 0)
    row.amount = Number(row.amount || 0)
    row.records = Number(row.records || 0)
    return row
  })
  const dataCfg = {
    fields: {
      rows: rowsSelected.value,
      columns: colsSelected.value,
      values: valsSelected.value,
      valueInCols: true,
    },
    meta: [
      ...dimensions.map(d => ({ field: d.value, name: d.label })),
      ...metrics.map(m => ({ field: m.value, name: m.label })),
    ],
    data,
  }
  const config = {
    width: s2Container.value.clientWidth,
    height: 480,
    hierarchyType: 'grid',
    style: { layoutWidthType: 'colAdaptive' },
    totals: { row: { showGrandTotals: true, showSubTotals: true }, col: { showGrandTotals: true, showSubTotals: true } },
  }
  if (s2) { s2.setDataCfg(dataCfg); s2.setOptions(config); s2.render(); return }
  s2 = new PivotSheet(s2Container.value, dataCfg, config)
  s2.render()
}

// 标签辅助
function labelOf(v) {
  const d = dimensions.find(d => d.value === v)
  return d ? d.label : v
}
function labelMetric(v) {
  const m = metrics.find(m => m.value === v)
  return m ? m.label : v
}

// 拖拽与顺序调整
const dragging = reactive({ fromArea: '', fromIndex: -1, field: '', type: '' })
function onPoolDragStart(type, field){ dragging.type = type; dragging.field = field; dragging.fromArea='pool'; dragging.fromIndex=-1 }
function onZoneDrop(area){
  const f = dragging.field
  if (!f) return
  if (area === 'rows' || area === 'cols') {
    if (!dimensions.some(d => d.value === f)) return
    if (area === 'rows') {
      colsSelected.value = colsSelected.value.filter(x => x !== f)
      if (!rowsSelected.value.includes(f)) rowsSelected.value = [...rowsSelected.value, f]
    } else {
      rowsSelected.value = rowsSelected.value.filter(x => x !== f)
      if (!colsSelected.value.includes(f)) colsSelected.value = [...colsSelected.value, f]
    }
  } else if (area === 'vals') {
    if (!metrics.some(m => m.value === f)) return
    if (!valsSelected.value.includes(f)) valsSelected.value = [...valsSelected.value, f]
  }
  dragging.fromArea=''; dragging.fromIndex=-1; dragging.field=''; dragging.type=''
}
function onChipDragStart(area, idx, f){ dragging.fromArea = area; dragging.fromIndex = idx; dragging.field = f; dragging.type = dimensions.some(d=>d.value===f)?'dim':'met' }
function onChipDrop(area, idx){
  const f = dragging.field
  if (!f) return
  const getList = (a)=> a==='rows'?rowsSelected.value: a==='cols'?colsSelected.value: valsSelected.value
  const setList = (a, list)=> { if(a==='rows') rowsSelected.value=[...list]; else if(a==='cols') colsSelected.value=[...list]; else valsSelected.value=[...list] }
  // 从来源移除
  if (dragging.fromArea && dragging.fromArea !== 'pool') {
    const fromList = getList(dragging.fromArea)
    const fromIdx = fromList.indexOf(f)
    if (fromIdx > -1) fromList.splice(fromIdx, 1)
    setList(dragging.fromArea, fromList)
  }
  // 插入到目标位置
  const target = getList(area)
  // 若目标已有该字段，先移除再插入到新位置
  const existIdx = target.indexOf(f)
  if (existIdx > -1) target.splice(existIdx, 1)
  target.splice(Math.max(0, Math.min(idx, target.length)), 0, f)
  setList(area, target)
  dragging.fromArea=''; dragging.fromIndex=-1; dragging.field=''; dragging.type=''
}
function removeField(area, f){
  if (area === 'rows') rowsSelected.value = rowsSelected.value.filter(x => x !== f)
  if (area === 'cols') colsSelected.value = colsSelected.value.filter(x => x !== f)
  if (area === 'vals') valsSelected.value = valsSelected.value.filter(x => x !== f)
}

watch([rowsSelected, colsSelected, valsSelected, range], () => { renderPivot() }, { deep: true })
</script>

<style scoped>
.page-wrap { padding: 16px; }
.toolbar { display: flex; gap: 12px; align-items: center; }
.mb-12 { margin-bottom: 12px; }
.w-240 { width: 240px; }
.w-220 { width: 220px; }
.s2-container { width: 100%; height: 480px; }
/* 拖拽面板样式 */
.panel { display: grid; grid-template-columns: 280px 1fr; gap: 12px; }
.pool { border-right: 1px solid #eee; padding-right: 12px; }
.pool .title { font-weight: 600; margin-bottom: 8px; }
.chips { display: flex; gap: 8px; flex-wrap: wrap; }
.chip { padding: 2px 8px; border-radius: 12px; background: #f3f4f6; cursor: move; user-select: none; }
.chip.dim { background: #e5f3ff; }
.chip.met { background: #e8f7ee; }
.chip .rm { margin-left: 6px; cursor: pointer; }
.zones { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; }
.zone { border: 1px dashed #cbd5e1; border-radius: 8px; padding: 8px; min-height: 60px; }
.zone-title { font-size: 12px; color: #64748b; margin-bottom: 6px; }
.mt-8 { margin-top: 8px; }
</style>


